package com.itheima.web.request; /**
 * @author Xiao
 * @date 2021/8/30
 */

import com.itheima.pojo.User;
import org.apache.commons.beanutils.BeanUtils;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Map;
import java.util.Set;

@WebServlet(name = "RegisterServlet", value = "/register")
public class RegisterServlet extends HttpServlet {
    /**
     * RegisterServlet
     *         获取注册提交过来的数据，将其封装成User对象。
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        Map<String, String[]> map = request.getParameterMap();
        User user = new User();
        /*//使用beanutils工具类快速封装数据
        try {
            BeanUtils.populate(user,map);
        } catch (Exception e) {
            e.printStackTrace();
        }*/
        //对每个参数逐一封装到user对象
        ArrayList<String> list = new ArrayList<>();
        Set<String> key = map.keySet();
        for (String s : key) {
            list.add(s);
        }
        String username = request.getParameter(list.get(0));
        String password = request.getParameter(list.get(1));
        String gender = request.getParameter(list.get(2));
        String birthday = request.getParameter(list.get(3));
        String[] hobby = request.getParameterValues(list.get(4));
        String city = request.getParameter(list.get(5));
        user.setUsername(username);
        user.setPassword(password);
        user.setGender(gender);
        user.setBirthday(birthday);
        user.setHobby(hobby);
        user.setCity(city);
        System.out.println(user);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request, response);
    }
}
